<?php
header('Content-Type: text/html; charset=utf-8');
error_reporting(E_ALL);
set_time_limit(0);
include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";
\ns_core\m_load::load("ns_core.m_config");
\ns_core\m_load::load("ns_model.message.message_queue");
\ns_core\m_load::load("ns_core.m_file");
\ns_core\m_load::load("ns_core.encrypt.m_aiqiyi_encrypt");
\ns_core\m_load::load_old("nn_logic/project_group/project_key.class.php");
//http公共入口
class http_import extends ns_model\message\message_queue
{
   public $str_cp_id = null;
    /**
     *  参数
     * @var unknown
     */
    public $mixed_params = null;

    private $int_num = 0;


    private $arr_vod_ids = array();
    private $arr_index_ids = array();
    private $arr_media_ids = array();
	
	 /**
     * 注入消息队列模板
     * @var unknown
     */
    public $arr_in_message = array(
        'base_info'=>array(
            'nns_message_time'=>'', //上游消息时间  年月日时分秒毫秒
            'nns_message_id'=>'',  //上游消息ID
            'nns_cp_id'=>'', //上游CP标示
            'nns_message_xml'=>'',  //上游原始的信息  可以为字符串 | xml | json
            'nns_message_content'=>'',  //上游解析后的信息  可以为字符串 | xml | json  生成队列的基本信息
            'nns_action'=>'', //操作 行为
            'nns_type'=>'', //消息 类型
            'nns_name'=>'',  //消息名称
            'nns_package_id'=>'',  //包ID（只对天威用 后期废用）
            'nns_xmlurlqc'=>'', //广州电信悦ME MD5摘要
            'nns_encrypt'=>'', //广州电信悦ME 加密串
            'nns_content_number'=>'1', //xml文件中包含的内容数量
            'nns_message_state'=>0,
        ), //基本信息（存储于nns_mgtvbk_message表中）
    );
	
	/**
	 * 初始化
	 */
	public function __construct()
	{
	    $arr_dir = explode('|', str_replace(array ('/','\\'), '|', __DIR__));
	    $this->str_cp_id = array_pop($arr_dir);
	    //加载 xml转为数组的np库
	    \ns_core\m_load::load_np("np_xml_to_array.class.php");
	    //初始化obj DC
	    m_config::get_dc();
	}
	
	public function init()
	{
	    $base_file_dir = dirname(dirname(dirname(dirname(dirname(dirname(__FILE__))))))."/data/temp/aiqiyi";
	    $result_files = m_file::get_files($base_file_dir);
	    if(!is_array($result_files) || empty($result_files))
	    {
	        return m_config::return_data(0,"路径[{$base_file_dir}];未获取到任何文件");
	    }
	    $result_files = array_chunk($result_files, 50);
	    $result_files = isset($result_files[0]) ? $result_files[0] : null;
	    if(!is_array($result_files) || empty($result_files))
	    {
	        return m_config::return_data(0,"路径[{$base_file_dir}];未获取到任何文件");
	    }
	    $str_exe = evn::get("php_execute_path") . ' -f ' . dirname(__FILE__) . '/import.php ';
	    foreach ($result_files as $value)
	    {
	        $value = base64_encode($value);
            if (substr(php_uname(), 0, 7) != "Windows")
            {
                //LINUX下执行
//                 $str_order = "{$str_exe}  $value > /dev/null &";
                $str_order = "{$str_exe}  $value > /dev/null & ";
            }
            else
            {
                //windows下执行
                $str_order = "{$str_exe}  $value > /dev/null & ";
            }
            usleep(50000);
            exec($str_order);
	    }
        return m_config::return_data(0,"OK");
	}
	
	
	/**
	 * 注入
	 * @return multitype:number |string
	 */
	public function init_v2($url)
	{
	    $url = base64_decode($url);
	    if(!file_exists($url))
	    {
	        return m_config::return_data(1,"获取文件路径不存在[{$url}]");
	    }
	    $data = file_get_contents($url);
	    $data = strlen($data) >0 ? $data : '';
	    if(!m_config::is_json($data))
	    {
	        @unlink($url);
	        return m_config::return_data(1,"内容非json[{$url}]");
	    }
	    $data = json_decode($data,true);
	    if(!is_array($data) || empty($data))
	    {
	        @unlink($url);
	        return m_config::return_data(1,"内容非数组[{$url}]");
	    }
	    $result_config = nl_project_key::query_by_key(m_config::get_dc(), "aiqiyi_info");
	    if($result_config['ret'] !=0)
	    {
	        return $result_config;
	    }
	    if(!isset($result_config['data_info']['nns_key_value']) || !m_config::is_json($result_config['data_info']['nns_key_value']))
	    {
	        return m_config::return_data(1,"aiqiyi_info 配置为空或者非法");
	    }
	    $result_config = json_decode($result_config['data_info']['nns_key_value'],true);
	    if(!isset($result_config['aiqiyi_url']) || strlen($result_config['aiqiyi_url']) <1)
	    {
	        return m_config::return_data(1,"aiqiyi_info 配置aiqiyi_url 为空或者未配置");
	    }
	    if(!isset($result_config['modId']) || strlen($result_config['modId']) <1)
	    {
	        return m_config::return_data(1,"aiqiyi_info 配置modId 为空或者未配置");
	    }
	    if(!isset($result_config['partnerId']) || strlen($result_config['partnerId']) <1)
	    {
	        return m_config::return_data(1,"aiqiyi_info 配置partnerId 为空或者未配置");
	    }
	    $modId = $result_config['modId'];
	    $partnerId = $result_config['partnerId'];
	    $token = m_aiqiyi_encrypt::encrypt($modId, $partnerId);
	    $aiqiyi_url = trim(rtrim(rtrim($result_config['aiqiyi_url'],'/'),'\\'));
	    $asset_data = null;
	    foreach ($data as $value)
	    {
	        $metas_info_aiqiyi_url="{$aiqiyi_url}/metas-info?t={$token}&id={$value}";
	        $result_metas_info = m_config::get_curl_content($metas_info_aiqiyi_url,30);
	        if($result_metas_info['ret'] !=0)
	        {
	            continue;
	        }
	        if(!isset($result_metas_info['data_info']) || !m_config::is_json($result_metas_info['data_info']))
	        {
	            continue;
	        }
	        $metas_info = json_decode($result_metas_info['data_info'],true);
    	    if(!isset($metas_info['code']) || $metas_info['code'] !='C00000' || !isset($metas_info['data']) || empty($metas_info['data']) || !is_array($metas_info['data']))
            {
                continue;
            }
            $id = isset($metas_info['data']['id']) ? $metas_info['data']['id'] : '';
            $total = (isset($metas_info['data']['total']) && $metas_info['data']['total'] >0) ? (int)$metas_info['data']['total'] : 1;
            $stype = (isset($metas_info['data']['stype']) && strlen($metas_info['data']['stype']) >0) ? $metas_info['data']['stype'] : '0';
            if(strlen($id)<1)
            {
                continue;
            }
            $for_num = ceil($total/120);
            $asset_data[$value]['asset'] = $metas_info['data'];
            if(substr($value, -2) != '01')
            {
//                 $asset_data[$value]['index'][1] = $metas_info['data'];
                continue;
            }
            for ($i=1;$i<=$for_num;$i++)
            {
                $ep_list_aiqiyi_url="{$aiqiyi_url}/ep-list?t={$token}&id={$value}&stype={$stype}&epType=0&pn={$i}&ps=120";
                $result_ep_list = m_config::get_curl_content($ep_list_aiqiyi_url,30);
                if($result_ep_list['ret'] !=0)
                {
                    continue;
                }
                if(!isset($result_ep_list['data_info']) || !m_config::is_json($result_ep_list['data_info']))
                {
                    continue;
                }
                $ep_list = json_decode($result_ep_list['data_info'],true);
                if(!isset($ep_list['code']) || $ep_list['code'] !='C00000' || !isset($ep_list['data']) || empty($ep_list['data']) || !is_array($ep_list['data']))
                {
                    continue;
                }
                foreach ($ep_list['data'] as $ep_value)
                {
                    if(!isset($ep_value['epOrder']) || $ep_value['epOrder'] <1)
                    {
                        continue;
                    }
                    $asset_data[$value]['index'][$ep_value['epOrder']] = $ep_value;
                }
            }
	        if(!isset($asset_data[$value]['index']) || !is_array($asset_data[$value]['index']) || empty($asset_data[$value]['index']))
	        {
	            unset($asset_data[$value]);
//                 $asset_data[$value]['asset']['total'] = 1;
// 	            $asset_data[$value]['index'][1] = $metas_info['data'];
	        }
	    }
	    if(empty($asset_data) || !is_array($asset_data))
	    {
	        @unlink($url);
	        return m_config::return_data(1,'数据为空');
	    }
	    $this->arr_in_message['base_info']['nns_cp_id'] = $this->str_cp_id;
	    $this->arr_in_message['base_info']['nns_action'] = 1;
	    foreach ($asset_data as $key=>$value)
	    {
	        $value['asset']['id'] =  $key;
	        $seice_xml = $this->make_serice_xml($value['asset']);
	        $result = $this->import($seice_xml,1);
	        foreach ($value['index'] as $index_value)
	        {
	            $index_xml = $this->make_index_xml($index_value, $key);
	            $result = $this->import($index_xml,2);
	        }
	    }
	    @unlink($url);
        return m_config::return_data(0,'ok');
	}
	
	
	public function import($str_xml,$type)
	{
	    if(strlen($str_xml) <1)
	    {
	        return m_config::return_data(1,'ok');
	    }
	    $result_cp_config = m_config::_get_cp_info($this->str_cp_id);
	    if($result_cp_config['ret'] !=0)
	    {
	        return $result_cp_config;
	    }
	    if(!isset($result_cp_config['data_info']) || empty($result_cp_config['data_info']) || empty($result_cp_config['data_info']))
	    {
	        return m_config::return_data(1,"获取CP[".$this->str_cp_id."]信息为空");
	    }
	    $arr_cp_config = $result_cp_config['data_info'];
        //原始数据存储的字段
        $data = $this->arr_in_message;
        $data['base_info']['nns_message_id'] = md5($str_xml);
        $data['base_info']['nns_message_time'] = microtime(true)*10000;
        $data['base_info']['nns_message_content'] = $str_xml;
        $data['base_info']['nns_type'] = $type;
        $data['base_info']['nns_action'] = 1;

        $obj_excute = new \m_message_inout();
        $result_ex = $obj_excute->query(array('nns_message_id'=>$data['base_info']['nns_message_id'],'nns_cp_id'=>$data['base_info']['nns_cp_id']));
        if($result_ex['ret'] !=0 || (isset($result_ex['data_info']) && !empty($result_ex['data_info']) && is_array($result_ex['data_info'])))
        {
            return $result_ex;
        }
        return $this->push($data);
	}
	
	public function make_serice_xml($arr_serice)
	{
	    $image1 = isset($arr_serice['picUrl']) ? trim($arr_serice['picUrl']) : '';
	    $image2 = isset($arr_serice['posterUrl']) ? trim($arr_serice['posterUrl']) : '';
	    $image = strlen($image1) >0 ? $image1 : $image2;
	    $arr_image = null;
	    if(strlen($image) >0)
	    {
	        $pathinfo = pathinfo($image);
	        
	        $image_h = $pathinfo['dirname'].'/'.$pathinfo['filename'].'_480_360'.".".$pathinfo['extension'];
	        $image_s = $pathinfo['dirname'].'/'.$pathinfo['filename'].'_260_360'.".".$pathinfo['extension'];
	        $image_v = $pathinfo['dirname'].'/'.$pathinfo['filename'].'_128_128'.".".$pathinfo['extension'];
	        $arr_image[md5($image)] = array('FileURL'=>$image,'Type'=>1,);
	        $arr_image[md5($image_h)] = array('FileURL'=>$image_h,'Type'=>4,);
	        $arr_image[md5($image_s)] = array('FileURL'=>$image_s,'Type'=>5,);
	        $arr_image[md5($image_v)] = array('FileURL'=>$image_v,'Type'=>6,);
	    }
	    $str_xml = '<?xml version="1.0" encoding="UTF-8"?>';
	    $str_xml.= '<ADI>';
	    $str_xml.=     '<Objects>';
	    $str_xml.=         '<Object ElementType="Series" ContentID="'.$arr_serice['id'].'" Code="'.$arr_serice['id'].'" Action="REGIST">';
	    $str_xml.=             '<Property Name="Name">'.$arr_serice['name'].'</Property>';
	    $str_xml.=             '<Property Name="OrderNumber">1</Property>';
	    $str_xml.=             '<Property Name="OriginalName">'.$arr_serice['name'].'</Property>';
	    $str_xml.=             '<Property Name="AliasName">'.$arr_serice['sname'].'</Property>';
	    $str_xml.=             '<Property Name="EnglishName"/>';
	    $str_xml.=             '<Property Name="SortName">'.$arr_serice['sname'].'</Property>';
	    $str_xml.=             '<Property Name="SearchName">'.$arr_serice['sname'].'</Property>';
	    $str_xml.=             '<Property Name="OrgAirDate"/>';
	    $str_xml.=             '<Property Name="ReleaseYear">'.date("Y-m-d",strtotime($arr_serice['time'])).'</Property>';
	    $str_xml.=             '<Property Name="LicensingWindowStart"/>';
	    $str_xml.=             '<Property Name="LicensingWindowEnd"/>';
	    $str_xml.=             '<Property Name="CPContentID">'.$this->str_cp_id.'</Property>';
	    $str_xml.=             '<Property Name="DisplayAsNew">0</Property>';
	    $str_xml.=             '<Property Name="DisplayAsLastChance">0</Property>';
	    $str_xml.=             '<Property Name="Macrovision">1</Property>';
	    $str_xml.=             '<Property Name="Price">1</Property>';
	    $str_xml.=             '<Property Name="VolumnCount">'.$arr_serice['total'].'</Property>';
	    $str_xml.=             '<Property Name="NewCount">'.$arr_serice['currCount'].'</Property>';
	    $str_xml.=             '<Property Name="Status">1</Property>';
	    $str_xml.=             '<Property Name="Description">'.$arr_serice['desc'].'</Property>';
	    $str_xml.=             '<Property Name="ContentProvider">'.$this->str_cp_id.'</Property>';
	    $str_xml.=             '<Property Name="KeyWords">'.$arr_serice['focusName'].'</Property>';
	    $str_xml.=             '<Property Name="OriginalCountry"></Property>';
	    $str_xml.=             '<Property Name="ActorDisplay">'.str_replace(',', '/', $arr_serice['persons']['mainActor']).'</Property>';
	    $str_xml.=             '<Property Name="DirectorDisplay">'.str_replace(',', '/', $arr_serice['persons']['director']).'</Property>';
	    $str_xml.=             '<Property Name="WriterDisplay">'.str_replace(',', '/', $arr_serice['persons']['writer']).'</Property>';
	    $str_xml.=             '<Property Name="Language"></Property>';
	    $str_xml.=             '<Property Name="Kind">'.$arr_serice['tagNames'].'</Property>';
	    $str_xml.=             '<Property Name="Duration">'.$arr_serice['eqLen'].'</Property>';
	    $str_xml.=             '<Property Name="CategoryName">'.$arr_serice['cname'].'</Property>';
	    $str_xml.=             '<Property Name="CategoryID"></Property>';
	    $str_xml.=             '<Property Name="PlayCount">'.$arr_serice['playCount'].'</Property>';
	    $str_xml.=             '<Property Name="CategorySort">0</Property>';
	    $str_xml.=             '<Property Name="Tags">26,</Property>';
	    $str_xml.=             '<Property Name="ViewPoint">'.$arr_serice['score'].'</Property>';
	    $str_xml.=             '<Property Name="StarLevel">6</Property>';
	    $str_xml.=             '<Property Name="Rating"/>';
	    $str_xml.=             '<Property Name="Awards"/>';
	    $str_xml.=             '<Property Name="Sort">0</Property>';
	    $str_xml.=             '<Property Name="Hotdegree">0</Property>';
	    $str_xml.=             '<Property Name="Reserve1"/>';
	    $str_xml.=             '<Property Name="Reserve1"/>';
	    $str_xml.=         '</Object>';
	    if(is_array($arr_image) && !empty($arr_image))
	    {
	        foreach ($arr_image as $image_key=>$image_value)
	        {
	            $str_xml.= '<Object ElementType="Picture" ContentID="'.$image_key.'" Code="'.$image_key.'" Action="REGIST">';
	            $str_xml.=     '<Property Name="FileURL">'.$image_value['FileURL'].'</Property>';
	            $str_xml.=     '<Property Name="Type">'.$image_value['Type'].'</Property>';
	            $str_xml.=     '<Property Name="Description"></Property>';
	            $str_xml.= '</Object>';
	        }
	    }
	    $str_xml.=     '</Objects>';
	    $str_xml.=     '<Mappings>';
	    if(is_array($arr_image) && !empty($arr_image))
	    {
	        foreach ($arr_image as $image_key=>$image_value)
	        {
        	    $str_xml.= '<Mapping ParentType="Picture" ParentID="'.$image_key.'" ElementType="Series" ElementID="'.$arr_serice['id'].'" ParentCode="'.$image_key.'" ElementCode="'.$arr_serice['id'].'" Action="REGIST" Type="1"/>';
	        }
	    }
	    $str_xml.=     '</Mappings>';
	    $str_xml.= '</ADI>';
	    return $str_xml;
	}
	
	public function make_index_xml($arr_index,$serice_id)
	{
	    $Program_id = $serice_id."_".$arr_index['epOrder'];
	    if(!isset($arr_index['epVid']) || !isset($arr_index['epVid']) || strlen($arr_index['epVid']) <1 || strlen($arr_index['epId'])<1)
	    {
	        return '';
	    }
	    $temp_playurl = $Program_id."_".$arr_index['epVid']."_".$arr_index['epId'];
	    $Movie_id = md5($temp_playurl);
	    $str_xml = '<?xml version="1.0" encoding="UTF-8"?>';
	    $str_xml.= '<ADI>';
	    $str_xml.=     '<Objects>';
	    $str_xml.=         '<Object ElementType="Program" ContentID="'.$Program_id.'" Code="'.$Program_id.'" Action="REGIST">';
	    $str_xml.=             '<Property Name="Name">'.$arr_index['epFocus'].'</Property>';
	    $str_xml.=             '<Property Name="CPContentID">'.$this->str_cp_id.'</Property>';
	    $str_xml.=             '<Property Name="OrderNumber">1</Property>';
	    $str_xml.=             '<Property Name="OriginalName">'.$arr_index['epFocus'].'</Property>';
	    $str_xml.=             '<Property Name="SortName">1</Property>';
	    $str_xml.=             '<Property Name="Sequence">'.$arr_index['epOrder'].'</Property>';
	    $str_xml.=             '<Property Name="SortName">1</Property>';
	    $str_xml.=             '<Property Name="SearchName">'.$arr_index['epFocus'].'</Property>';
	    $str_xml.=             '<Property Name="ActorDisplay">'.str_replace(',', '/', $arr_index['persons']['mainActor']).'</Property>';
	    $str_xml.=             '<Property Name="WriterDisplay">'.str_replace(',', '/', $arr_index['persons']['writer']).'</Property>';
	    $str_xml.=             '<Property Name="Macrovision">1</Property>';
	    $str_xml.=             '<Property Name="Status">1</Property>';
	    $str_xml.=             '<Property Name="SourceType">1</Property>';
	    $str_xml.=             '<Property Name="SeriesFlag">1</Property>';
	    $str_xml.=             '<Property Name="ContentProvider">'.$this->str_cp_id.'</Property>';
	    $str_xml.=             '<Property Name="Duration">'.$arr_index['epLen'].'</Property>';
	    $str_xml.=         '</Object>';
	    $str_xml.=         '<Object ElementType="Movie" ContentID="'.$Movie_id.'" Code="'.$Movie_id.'" Action="REGIST">';
	    $str_xml.=             '<Property Name="FileURL">'.$temp_playurl.'</Property>';
	    $str_xml.=             '<Property Name="CPContentID">'.$this->str_cp_id.'</Property>';
	    $str_xml.=             '<Property Name="SourceDRMType">0</Property>';
	    $str_xml.=             '<Property Name="DestDRMType">0</Property>';
	    $str_xml.=             '<Property Name="AudioType">1</Property>';
	    $str_xml.=             '<Property Name="ScreenFormat">1</Property>';
	    $str_xml.=             '<Property Name="ClosedCaptioning">1</Property>';
	    $str_xml.=             '<Property Name="Tags">26,</Property>';
	    $str_xml.=             '<Property Name="Duration">'.$arr_index['epLen'].'</Property>';
	    $str_xml.=             '<Property Name="FileSize">8080</Property>';
	    $str_xml.=             '<Property Name="BitRateType">4500</Property>';
	    $str_xml.=             '<Property Name="VideoType">1</Property>';
	    $str_xml.=             '<Property Name="FileType">ts</Property>';
	    $str_xml.=             '<Property Name="FrameRate">0</Property>';
	    $str_xml.=             '<Property Name="Dimensions">0</Property>';
	    $str_xml.=             '<Property Name="AudioEncodingType">4</Property>';
	    $str_xml.=             '<Property Name="Resolution">528*576</Property>';
	    $str_xml.=             '<Property Name="MediaMode">1</Property>';
	    $str_xml.=             '<Property Name="SystemLayer">1</Property>';
	    $str_xml.=             '<Property Name="ServiceType"/>';
	    $str_xml.=             '<Property Name="Domain"/>';
	    $str_xml.=             '<Property Name="Hotdegree">0</Property>';
	    $str_xml.=         '</Object>';
	    $str_xml.=     '</Objects>';
	    $str_xml.=     '<Mappings>';
	    $str_xml.=         '<Mapping ParentType="Series" ParentID="'.$serice_id.'" ElementType="Program" ElementID="'.$Program_id.'" ParentCode="'.$serice_id.'" ElementCode="'.$Program_id.'" Action="REGIST" Type="1">';
	    $str_xml.=             '<Property Name="Sequence">'.$arr_index['epOrder'].'</Property>';
	    $str_xml.=         '</Mapping>';
	    $str_xml.=         '<Mapping ParentType="Program" ParentID="'.$Program_id.'" ElementType="Movie" ElementID="'.$Movie_id.'" ParentCode="'.$Program_id.'" ElementCode="'.$Movie_id.'" Action="REGIST" Type="1"/>';
	    $str_xml.=     '</Mappings>';
	    $str_xml.= '</ADI>';
	    return $str_xml;
	}
	
	/**
	 * 类销毁
	 */
	public function __destruct()
	{
	    m_config::base_write_log('message','request',"-----------消息接收结束-----------",m_config::return_child_path(__FILE__));
	}
}
if(isset($_SERVER['argv'][1]) && !empty($_SERVER['argv'][1]))
{
    $http_import = new http_import();
    $result = $http_import->init_v2($_SERVER['argv'][1]);
}
else
{
    $http_import = new http_import();
    $result = $http_import->init();
}
var_dump($result);